package com.wnxy.admin.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.common.handler.Asserts;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.common.handler.SysBusinessEnum;
import com.wnxy.admin.common.util.AliOssUtil;
import com.wnxy.admin.dto.MaintenancePersonDto;
import com.wnxy.admin.dto.PageResult;
import com.wnxy.admin.entity.MaintenancePersonnel;
import com.wnxy.admin.service.IMaintenancePersonnelService;
import lombok.RequiredArgsConstructor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author All
 * @since 2023-11-29
 */
@RestController
@RequestMapping("/maintenance-personnel")
@RequiredArgsConstructor
public class MaintenancePersonnelController {

    private final IMaintenancePersonnelService maintenancePersonnelServiceImpl;
    private final AliOssUtil aliOssUtil;

    /*
     *  数据导入
     * */
    @PostMapping("/import")
    public ResponseResult importEntityList(@RequestParam("file") MultipartFile file) {
        try {
            // 判断文件类型是否为Excel
            if (!isExcelFile(file)) {
                return ResponseResult.fail(BusinessEnum.INVALID_FILE_TYPE);
            }

            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);

            List<MaintenancePersonnel> list = ExcelImportUtil.importExcel(
                    file.getInputStream(),
                    MaintenancePersonnel.class, params);

            // 过滤掉空行
            List<MaintenancePersonnel> filteredList = list.stream()
                    .filter(entity -> isNotEmpty(entity))
                    .collect(Collectors.toList());

            // 遍历集合向数据库追加运维人员
            filteredList.forEach(e -> maintenancePersonnelServiceImpl.addPerson(e));

            return ResponseResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(BusinessEnum.IMPORT_FAILED);
        }
    }

    private boolean isExcelFile(MultipartFile file) {
        try {
            // 尝试用Apache POI加载Workbook，如果成功则表示是Excel文件
            WorkbookFactory.create(file.getInputStream());
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    // 判断 MaintenancePersonnel 实体是否为空
    private boolean isNotEmpty(MaintenancePersonnel entity) {
        return entity != null &&
                ( StringUtils.isNotEmpty(entity.getUserName()) &&
                        StringUtils.isNotEmpty(entity.getCertificate()) &&
                        StringUtils.isNotEmpty(entity.getContactEmail()) &&
                        entity.getStatus() != null &&
                        StringUtils.isNotEmpty(entity.getPersonnelCategory()));
    }

    /*
    *  数据导出
    * */
    @GetMapping("/export")
    public void export(ModelMap map,
                                 HttpServletRequest request,
                                 HttpServletResponse response) {
        List<MaintenancePersonnel> maintenancePersonnelList = maintenancePersonnelServiceImpl.list();
        ExportParams params = new ExportParams("运维人员列表", "运维人员列表", ExcelType.XSSF);
        map.put(NormalExcelConstants.DATA_LIST, maintenancePersonnelList);
        map.put(NormalExcelConstants.CLASS, MaintenancePersonnel.class);
        map.put(NormalExcelConstants.PARAMS, params);
        map.put(NormalExcelConstants.FILE_NAME, "maintenancePersonnelList");
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    /*
     *  清空图片
     * */
    @GetMapping("/clearPictures")
    public ResponseResult clearPictures(String image) {
        try {
            aliOssUtil.deleteImg(image);
        } catch (IllegalArgumentException  ie) {
            Asserts.fail(ObjectUtils.isEmpty(ie), BusinessEnum.IMAGE_PATH_IS_WRONG);
        }catch (Exception e) {
            Asserts.fail(ObjectUtils.isEmpty(e), SysBusinessEnum.SYSTEM_BUSY);
        }
        return ResponseResult.ok();
    }

    /*
     *  获取编辑运维人员
     * */
    @GetMapping("/getIdlePeople/{operatorId}")
    public ResponseResult getIdlePeople(@PathVariable("operatorId") Long operatorId) {
        List<MaintenancePersonnel> idlePeople = maintenancePersonnelServiceImpl.getIdlePeople(operatorId);
        return ResponseResult.ok(idlePeople);
    }

    /*
     *  查询运维人员(分页)
     * */
    @GetMapping("/queryPerson")
    public ResponseResult queryPerson(@ModelAttribute MaintenancePersonDto maintenancePersonDto) {
        PageResult page = maintenancePersonnelServiceImpl.queryPerson(maintenancePersonDto);
        return ResponseResult.ok(page);
    }

    /*
     *  编辑运维人员
     * */
    @PutMapping("/editPerson")
    public ResponseResult editPerson(@RequestBody MaintenancePersonnel maintenancePersonnel) {
        maintenancePersonnelServiceImpl.editPerson(maintenancePersonnel);
        return ResponseResult.ok();
    }

    /*
     *  删除/批量 运维人员
     * */
    @DeleteMapping("/removeBatchPerson")
    public ResponseResult removeBatchPerson(@RequestBody List<Long> maintenancePersonnelIds) {
        maintenancePersonnelServiceImpl.removeBatchPerson(maintenancePersonnelIds);
        return ResponseResult.ok();
    }

    /*
     *  新增运维人员
     * */
    @PostMapping("/addPerson")
    public ResponseResult addPerson(@RequestBody MaintenancePersonnel maintenancePersonnel) {
        maintenancePersonnelServiceImpl.addPerson(maintenancePersonnel);
        return ResponseResult.ok();
    }
}
